package com.bainuo.doctor.common.image_support.imghandle.rcpickview;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bainuo.doctor.common.R;
import com.bainuo.doctor.common.image_support.imghandle.Bean.AudioUploadInfo;
import com.bainuo.doctor.common.image_support.imghandle.Bean.ImageUploadInfo;
import com.bainuo.doctor.common.image_support.imghandle.ImageHandler;
import com.bainuo.doctor.common.image_support.imghandle.uploader.FileUploader;
import com.bainuo.doctor.common.image_support.imghandle.uploader.IFileUpload;
import com.bainuo.doctor.common.image_support.imghandle.uploader.UploadTask;
import com.bainuo.doctor.common.image_support.imghandle.view.PickerItemViewLoader;
import com.bainuo.doctor.common.network_engine.UpFileServerApi;
import com.bainuo.doctor.common.util.AudioPlayer;
import com.bainuo.doctor.common.util.MyUtil;
import com.bainuo.doctor.common.util.ViewUtil;
import com.blankj.utilcode.utils.LogUtils;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by bainuo on 2017/12/25.
 */

public class RCPickerView extends RecyclerView {

    public ImageHandler imageHandler;
    public FileUploader fileUploader;
    public int maxCount = 9;
    MyUtil.LoopHandler voiceRetryLoop;
    private List<UploadTask> listTask = new ArrayList<>();
    private MyAdapter mAdapter;

    Map<String,MyAdapter.Holder> holderMap = new HashMap();


    public RCPickerView(Context context) {
        super(context);
        init(context);
    }

    public RCPickerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }


    public void setOrientation(int orientation) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(orientation);
        setLayoutManager(linearLayoutManager);
    }


    public void setUploadFileApi(UpFileServerApi imageUploader, UpFileServerApi voiceUploader) {
        if (imageHandler != null)
            imageHandler.setUploadFileApi(imageUploader);

        //语音文件上传
        fileUploader = new FileUploader(voiceUploader);
        fileUploader.setUploadListener(new IFileUpload.Listener() {
            @Override
            public void onUploadFinish(UploadTask task) {

            }

            @Override
            public void onUploadSuccess(UploadTask task) {

                MyAdapter.Holder holder = holderMap.get(task.id);
                if (holder != null){
                    holder.setState(UploadTask.STATE_COM);
                }

                //文件上传成功后　设置url
//                String id = getLastPath(task.getUrl());
//                String newPath = manager.addDownloadFile(id,itemInfo.getPath());
            }

            @Override
            public void onUploadFailed(final UploadTask task) {
                MyAdapter.Holder holder = holderMap.get(task.id);
                if (holder != null){
                    holder.setState(UploadTask.STATE_FAILED);
                }

                //上传文件失败 重传
//                voiceRetryLoop = MyUtil.runLoop(5000, new MyUtil.Loop() {
//                    @Override
//                    public boolean doexec() {
//                        task.setState(UploadTask.STATE_PRE);
//                        fileUploader.uploadFile(task);
//                        return false;
//                    }
//                });
            }

            @Override
            public void onUploadProgress(UploadTask task) {
                MyAdapter.Holder holder = holderMap.get(task.id);
                if (holder != null)
                    holder.setProgress(task.getProgress());

                LogUtils.e("audio onUploadProgress"+task.getProgress());
            }
        });

    }

    private AudioPlayer audioPlayer;
    public void init(final Context context) {

        mAdapter = new MyAdapter();
        setAdapter(mAdapter);
        setOrientation(LinearLayoutManager.HORIZONTAL);



        //初始化音频播放器
        audioPlayer = new AudioPlayer(context,null);
        audioPlayer.setOnCompletionCallBack(new AudioPlayer.OnCompletionCallBack() {
            @Override
            public void onCompletionCallBack(int type) {
//                INT_START
//                if (currentPlayItem != null)
//                    currentPlayItem.playAnimate(false);

                MyAdapter.Holder holder = holderMap.get(audioPlayer.tag);
                if (holder != null){
                    playAnimate(holder.mIvVoice,false);
                }
            }
        });

        //创建图片处理器
        imageHandler = new ImageHandler((Activity) context, null);
        imageHandler.imagePicker.setMaxPictures(maxCount);
        imageHandler.setImagHandlerListener(new ImageHandler.IImagHandlerListener() {
            @Override
            public void onPickerReult(boolean success, List<ImageUploadInfo> info) {
                listTask.addAll(info);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onImageCropReult(boolean success, ImageUploadInfo info) {

            }

            @Override
            public void onUploadResult(boolean success, ImageUploadInfo info) {

                MyAdapter.Holder holder = holderMap.get(info.getId());
                if (holder == null) return;

                //如果loader存在
                if (success) {

                    //上传成功
                    holder.setState(info.STATE_COM);
//                    if (listener != null) {
//                            listener.onImageUploadSuccess(info);
//                            //如果全部上传完成 则回调数据
//                            if (isAllComplete()) {
//                                listener.onImagesUploadSuccess(imageInfos);
//                            }
//                    }
                } else {

                    //设置上传失败
                    holder.setState(info.STATE_FAILED);
//                    if (listener != null)
//                        listener.onImageUploadFailed(info);
                }

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onUploadProgress(String id, int progress) {
                MyAdapter.Holder holder = holderMap.get(id);
                if (holder != null)
                    holder.setProgress(progress);
            }
        });
    }


    public void addImage(){
        imageHandler.imagePicker.setMaxPictures(maxCount - getImageCount());
        imageHandler.imagePicker.pickFromAlbum();
    }

    public void stopAudio(){
        if (audioPlayer != null)
            audioPlayer.stopAudio();
    }

    public void setVoice(String path, int duration) {

        final AudioUploadInfo task = new AudioUploadInfo();
        task.setSrcPath(path);
        task.setUploadPath(path);
        task.setDuration(duration);
        if (fileUploader != null) {

            //延迟调用上传 否则音频文件完全生成
            MyUtil.runLoop(300, new MyUtil.Loop() {
                @Override
                public boolean doexec() {
                    fileUploader.uploadFile(task);
                    return false;
                }
            });
//            fileUploader.uploadFile(task);
        }

        if (listTask.size()>0 && !listTask.get(0).isImageType()){
            listTask.set(0,task);
        }else{
            listTask.add(0,task);
        }
        mAdapter.notifyDataSetChanged();
    }


//    public void addVoice(String path, int duration) {
        //上传语音
//        AudioUploadInfo task = new AudioUploadInfo();
//        task.setSrcPath(path);
//        task.setUploadPath(path);
//        task.setDuration(duration);
//        if (fileUploader != null)
//            fileUploader.uploadFile(task);
//
//
//
//        listTask.set(0,task);
//
//        listTask.add(0,task);
//        mAdapter.notifyDataSetChanged();
//    }


    public List<UploadTask> getTaskInfos() {
        return listTask;
    }

    public boolean isAllComplete() {
        boolean complete = true;
        //检查是否全部任务完成
        for (UploadTask task : listTask) {
            if (!task.isUploadComplete()) {
                complete = false;
            }
        }
        return complete;
    }

    public int getImageCount(){
        int count = 0;
        for (UploadTask task : listTask) {
            if (task.isImageType()) {
                count++;
            }
        }
        return count;
    }


    public void clear(){
        listTask.clear();
        mAdapter.notifyDataSetChanged();
    }


    class MyAdapter extends Adapter {

        private boolean rounded = true;
        int index = 0;

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.item_rcpicker, null);
            Holder holder = new Holder(view);
            holder.mSd.setTag("标识"+index++);
            LogUtils.e("onCreateViewHolder--->"+((Holder) holder).mSd.getTag());

            return holder;
        }



        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            final Holder myHodler = (Holder) holder;
            final UploadTask task = listTask.get(position);

            //缓存视图 用于更新上传进度
            holderMap.put(task.id,myHodler);

            //设置为不重用
//            myHodler.setIsRecyclable(false);

            if (task.isImageType()) {
                ImageUploadInfo info = (ImageUploadInfo) task;
                myHodler.mSd.setImageURI("file://" + info.getSrcPath());
                myHodler.mSd.setVisibility(VISIBLE);
                myHodler.mLyVoice.setVisibility(INVISIBLE);
            } else {
                AudioUploadInfo info = (AudioUploadInfo)task;
                myHodler.mLyVoice.setVisibility(VISIBLE);
                myHodler.mSd.setImageURI("res://com.bainuo/"+ R.mipmap.icon_qztjyybj);
                myHodler.mTvVoice.setText(String.format("%02d:%02d",info.getDuration()/60,info.getDuration()%60));
            }

            //设置进度状态
            myHodler.setProgress(task.getProgress());
            myHodler.setState(task.getState());


            myHodler.id = task.id;
            myHodler.task = task;

            //设置删除item
            myHodler.closeView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    UploadTask tk = myHodler.task;
                    listTask.remove(tk);
                    //取消文件上传
                    imageHandler.imageUpload.cancelRequest(tk.id);
                    fileUploader.cancelRequest(tk.id);
                    holderMap.remove(tk.id);
                    mAdapter.notifyDataSetChanged();
                }
            });

            //重试上传
            myHodler.retryView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    myHodler.setState(UploadTask.STATE_PRE);
                    UploadTask tk = myHodler.task;
                    if (tk.isImageType()) {
                        imageHandler.imageUpload.cancelRequest(((ImageUploadInfo) tk).getId());
                        imageHandler.imageUpload.uploadFile(tk);
                    } else {
                        fileUploader.cancelAllRequest();
                        fileUploader.uploadFile(tk);
                    }


                }
            });

            myHodler.mSd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (!task.isImageType()){

                        if (AudioPlayer.isPlayer){
                            audioPlayer.tag = null;
                            audioPlayer.stopAudio();
                            playAnimate(myHodler.mIvVoice,false);
                        }else{
                            audioPlayer.tag = task.id;
                            audioPlayer.playAudio(task.getSrcPath());
                            playAnimate(myHodler.mIvVoice,true);
                        }
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return listTask.size();
        }

        @Override
        public void onViewRecycled(ViewHolder holder) {
            super.onViewRecycled(holder);
            LogUtils.e("onViewRecycled--->"+((Holder) holder).mSd.getTag());
            Holder myHoler = (Holder)holder;
            holderMap.remove(myHoler.id);

            if (AudioPlayer.isPlayer && myHoler.id.equals(audioPlayer.tag)){
                audioPlayer.stopAudio();
                playAnimate(myHoler.mIvVoice,false);
            }
        }

        class Holder extends ViewHolder {

            public String id;
            public UploadTask task;

            SimpleDraweeView mSd;
            TextView mTvVoice;
            LinearLayout mLyVoice;
            ImageView mIvVoice;
            SimpleDraweeView maskView;
            ImageView retryView;
            ImageView closeView;


            public Holder(View itemView) {
                super(itemView);

                mSd = itemView.findViewById(R.id.itemnode_sd);
                mTvVoice = (TextView) itemView.findViewById(R.id.itemnode_tv_voice);
                mLyVoice = itemView.findViewById(R.id.itemnode_ly_voice);
                maskView = itemView.findViewById(R.id.itemnode_mask);
                retryView = itemView.findViewById(R.id.itemnode_retry);
                closeView = itemView.findViewById(R.id.itemnode_close);
                mIvVoice = itemView.findViewById(R.id.itemnode_iv_voice);
            }


            /**
             * 设置圆角
             */
            public void setMaskRound(boolean round) {
                if (round == rounded)
                    return;

                if (!rounded) {
                    //四个角都为圆角
                    float[] corners = maskView.getHierarchy().getRoundingParams().getCornersRadii();
                    maskView.getHierarchy().setRoundingParams(RoundingParams.fromCornersRadii(corners[7], corners[7], corners[7], corners[7]));
                } else {
                    //左上与右上 应该设置为无圆角
                    float[] corners = maskView.getHierarchy().getRoundingParams().getCornersRadii();
                    maskView.getHierarchy().setRoundingParams(RoundingParams.fromCornersRadii(0, 0, corners[7], corners[7]));
                }
                rounded = round;
            }


            /**
             * 设置进度条
             */
            public void setProgress(int progress) {

//                setMaskRound(progress < 5);
//        maskView.setAspectRatio(((float)progress)/100);
                //设置进度高度
                if (maskView.getWidth() != 0)
                    ViewUtil.setViewHeight(maskView, mSd.getWidth() * (100 - progress) / 100);
            }


            /**
             * 设置状态
             */
            public void setState(int state) {

                closeView.setVisibility(View.VISIBLE);

                if (state == UploadTask.STATE_FAILED) {
                    //上传失败 显示重试
                    retryView.setVisibility(View.VISIBLE);
                    ViewUtil.setViewHeight(maskView, maskView.getWidth());
                    setMaskRound(true);
                } else if (state == UploadTask.STATE_COM) {

                    //设置完成状态
                    retryView.setVisibility(View.GONE);
                    maskView.setVisibility(View.GONE);
                } else {

                    //设置正在下载状态
                    retryView.setVisibility(View.GONE);
                    maskView.setVisibility(View.VISIBLE);
                }
            }

            /**
             * 重置所有状态
             */
            public void reset() {
                retryView.setVisibility(View.GONE);
                maskView.setVisibility(View.GONE);
                closeView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 播放语音动画
     * @param state
     */
    public void playAnimate(ImageView view,boolean state){

        view.setImageResource(R.drawable.voice_play_ani);
        if (state){
            AnimationDrawable animationDrawable = (AnimationDrawable) view.getDrawable();
            animationDrawable.start();
        }else{
            AnimationDrawable animationDrawable = (AnimationDrawable) view.getDrawable();
            animationDrawable.stop();
            view.setImageResource(R.drawable.icon_yybf3);
        }
    }

    public void destory() {

    }

}
